<?PHP
#require_once('../singleton.class.php');
require_once('constants.php');

class Database# extends Singleton
{
	private static $instance;
	private $connection;
	
	private function __construct(){}
	public function __destruct()
	{
		$this->disconnect();
	}
	
	public static function getInstance()
	{
			if(!isset(self::$instance))
			{
					$class = __CLASS__;
					self::$instance = new $class;
			}
			return self::$instance;
	}
	
	public function __clone()
	{
			trigger_error('Unable to clone singleton', E_USER_ERROR);
	}
	
	public function connect()
	{
		if(!$this->isConnected())
		{
			$this->connection = mysql_connect(DatabaseConstants::DATABASE_HOST, DatabaseConstants::DATABASE_USER, DatabaseConstants::DATABASE_PASSWORD, false);
			mysql_select_db(DatabaseConstants::DATABASE_NAME, $this->connection);
		}
	}
	
	public function disconnect()
	{
		if($this->isConnected())
		{
			mysql_close($this->connection);
		}
	}
	
	public function isConnected()
	{
		return isset($this->connection);
	}
	
	public function selectAssoc($query)
	{
		$items = Array();
		$res = $this->rawQuery($query);
		
		while($item = mysql_fetch_assoc($res))
		{
			$items[] = $item;
		}
		
		return $items;
	}
	
	public function insert($table, $values)
	{
		$this->makeSafe($values);
		
		$keys = array_keys($values);
		$vals = array_values($values);
		$query = "INSERT INTO $table(".implode($keys,',').") VALUES(".implode($values,',').")";
		
		$this->rawQuery($query);
	}
	
	public function count($table, $conditions)
	{
		$query = "SELECT id FROM $table WHERE ";
		$this->makeSafe($conditions);
		$queryCnd = Array();
		foreach($conditions as $k=>$v)
		{
			$queryCnd[] = "$k=$v";
		}
		
		$query .= implode(" AND ",$queryCnd);
		
		$r = $this->rawQuery($query);
		$count = mysql_num_rows($r);
		return $count;
	}
	
	private function makeSafe(&$value)
	{
		if(!is_array($value))
		{
			$value = mysql_real_escape_string($value);
		}
		else
		{
			foreach($value as $k=>$v)
			{
				if(!is_numeric($v))
				{
					$value[$k] = '\''.mysql_real_escape_string($v).'\'';
				}
			}
		}
	}
	
	private function rawQuery($query)
	{
		return mysql_query($query,$this->connection);
	}
}
?>